package com.bakend.modules.sys.controller;


import com.alibaba.fastjson.JSON;
import com.bakend.common.utils.JwtUtils;
import com.bakend.modules.sys.entity.User;
import com.bakend.modules.sys.entity.UserInfo;
import com.bakend.modules.sys.service.UserInfoService;
import com.bakend.modules.sys.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * (User)表控制层
 *
 * @author makejava
 * @since 2021-05-02 03:28:59
 */
@RestController
@RequestMapping("user")
public class UserController extends ApiController {
    @Autowired
    private PasswordEncoder passwordEncoder;
    /**
     * 服务对象
     */
    @Resource
    private UserService userService;

    private UserInfoService userInfoService;

    /**
     * 分页查询所有数据
     *
     * @param page 分页对象
     * @param user 查询实体
     * @return 所有数据
     */
    @GetMapping("all")
    public R selectAll(Page<User> page, User user) {
        return success(this.userService.page(page, new QueryWrapper<>(user)));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public R selectOne(@PathVariable Serializable id) {
        return success(this.userService.getById(id));
    }
    /**
     * 通过主键查询单条数据
     *
     * @return 单条数据
     */
    @GetMapping("queryByName/{name}")
    public R queryByName(@PathVariable String name) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .like(User::getUserName,name);
        List<User> list = userService.list(wrapper);
        return success(list);
    }
    /**
     * 通过主键查询单条数据
     *
     * @return 单条数据
     */
    @GetMapping("addfriend/{userCode}")
    public R addFriend(@PathVariable String userCode) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(User::getUserCode,userCode);
        User one = userService.getOne(wrapper);
        if(one==null){
            return failed("好友不存在");
        }
        Object credentials = SecurityContextHolder.getContext().getAuthentication().getCredentials();
        if(credentials==null){
            return failed("未登录");
        }
        String token = (String) credentials;
        String headerByBase64 = JwtUtils.getHeaderByBase64(token);
        Object parse = JSON.parse(headerByBase64);
        if(parse==null){
            return failed("token不正确");
        }
        Map map = (Map) parse;
        String fromUserCode = (String) map.get(JwtUtils.UserIdKey);
        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
        userInfoQueryWrapper.lambda()
                .eq(UserInfo::getUserCode,fromUserCode);
        UserInfo one1 = userInfoService.getOne(userInfoQueryWrapper);
        if(one1!=null){
            String friendsStr = one1.getFriends();
            String substring = friendsStr.substring(1, friendsStr.length() - 1);
            String[] split = substring.split(",");
            for (String s : split) {
                if(one.getId().toString().equals(s)){
                    return failed("好友已经存在");
                }
            }
            String s = substring + "," + one.getId();
            one1.setFriends("["+s+"]");
            userInfoService.updateById(one1);
        }else {
            UserInfo userInfo = new UserInfo()  ;
            userInfo.setUserCode(fromUserCode);
            userInfo.setFriends("["+one.getId()+"]");
            userInfoService.save(userInfo);
        }
        return success("添加好友成功");
    }

    /**
     * 新增数据
     *
     * @param user 实体对象
     * @return 新增结果
     */
    @PostMapping("insert")
    public R insert(@RequestBody User user) {
        user.setPwd(passwordEncoder.encode(user.getPwd()));
        return success(this.userService.save(user));
    }

    /**
     * 修改数据
     *
     * @param user 实体对象
     * @return 修改结果
     */
    @PutMapping
    public R update(@RequestBody User user) {
        return success(this.userService.updateById(user));
    }

    /**
     * 删除数据
     *
     * @return 删除结果
     */
    @GetMapping("delete/{id}")
    public R delete(@PathVariable int id) {
        return success(this.userService.removeById(id));
    }

    @GetMapping("/friends")
    public R searchFriend(@PathVariable String userName){
        Object credentials = SecurityContextHolder.getContext().getAuthentication().getCredentials();
        if(credentials==null){
            return failed("未登录");
        }
        String token = (String) credentials;
        String headerByBase64 = JwtUtils.getHeaderByBase64(token);
        Object parse = JSON.parse(headerByBase64);
        if(parse==null){
            return failed("token不正确");
        }
        Map map = (Map) parse;
        String fromUserCode = (String) map.get(JwtUtils.UserIdKey);
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(UserInfo::getUserCode,fromUserCode);
        UserInfo one = userInfoService.getOne(queryWrapper);
        List<User> friends = new ArrayList<>();
        if(one!=null){
            String fStr = one.getFriends();
            if(StringUtils.isEmpty(fStr)){
                return success(friends);
            }
            String substring = fStr.substring(1, fStr.length() - 1);
            String[] split = substring.split(",");
            Arrays.asList(split).stream().forEach(s->{
                User byId = userService.getById(Integer.parseInt(s));
                if(byId!=null) friends.add(byId);
            });
            return success(friends);
        }
        return success(friends);
    }
}